<script lang="ts" setup>
/**
 * Props
 * @width {String} 裁剪宽度 单位：PX
 * 默认 500px
 *
 * @height {String} 裁剪高度 单位：PX
 * 默认 500px
 *
 * @radius {String} 裁剪圆角 单位：PX
 * 默认 0px
 *
 * @limitSize {String} 选择的图片大小 单位：MB
 * 默认 5MB
 *
 * @uploaderPath {String} 裁剪后上传的服务器地址
 *
 * Emits
 * @image {String} 上传服务器后返回的图片地址
 *
 * Expose
 * @cropper 选择图片
 */
import { ref } from 'vue'
import { postFileReq } from '@U/common'
import { Msg, MsgLoading, MsgLoadingClear } from '@C/Msg'
import { getWeiXinPrivacyAuthorization } from '@U/Auth'
import QfImageCropper from '@/static/qf-image-cropper/qf-image-cropper.vue'
import type { IObj } from '@/interface'

const props = defineProps({
  width: {
    type: String,
    required: false,
    default: '500',
  },
  height: {
    type: String,
    required: false,
    default: '500',
  },
  radius: {
    type: String,
    required: false,
    default: '0',
  },
  limitSize: {
    type: String,
    required: false,
    default: '5',
  },
  uploaderPath: {
    type: String,
    required: false,
    default: '/api/file/upload',
  },
})
const emits = defineEmits(['image'])
defineExpose({
  // 获取微信授权
  cropper() {
    getWeiXinPrivacyAuthorization(() => {
      uni.chooseImage({
        count: 1,
        success(res) {
          // 选择的图片路径
          const { tempFilePaths } = res
          const path: string = tempFilePaths[0]
          uni.getFileInfo({
            filePath: path,
            success: async (info) => {
              if (info.size >= +props.limitSize * 1024 * 1024) return Msg({ icon: 'error', msg: `图片最大${props.limitSize}MB` })
              imgSrc.value = path
              show.value = true
            },
          })
        },
      })
    })
  },
})

// 展示
const show = ref(false)

// 待裁剪图片路径
const imgSrc = ref('')

// 裁剪后路径
const handleCrop = async (event: IObj) => {
  const { tempFilePath } = event
  await MsgLoading('上传中')
  await postFileReq(props.uploaderPath, tempFilePath)
      .then(res => {
        const { statusCode, data } = res
        const nowData = JSON.parse(data)
        if (statusCode === 200 && nowData.code === 200) {
          MsgLoadingClear()
          show.value = false
          emits('image', nowData.data[0])
          imgSrc.value = ''
        }
      })
      .catch(() => MsgLoadingClear({ msg: '上传失败', icon: 'error' }))
}
</script>

<template>
  <div class="image_cropper_box">
    <div v-if="show" class="crop_box">
      <QfImageCropper
        :height="+height"
        :radius="+radius"
        :src="imgSrc"
        :width="+width"
        @crop.stop="handleCrop"
      />
    </div>
  </div>
</template>
